package com.wstuo.common.tools.dao;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.wstuo.common.tools.dto.CostDTO;
import com.wstuo.common.tools.entity.Cost;
import com.wstuo.common.tools.util.ToolsConstant;
import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.util.DaoUtils;
import com.wstuo.common.util.StringUtils;
import com.wstuo.common.util.TimeUtils;

/**
 * Cost DAO class
 * @author WSTUO
 *
 */
public class CostDAO extends BaseDAOImplHibernate<Cost> implements ICostDAO{
	
	/**
	 * 成本分页查询
	 * @param queryDto
	 * @param start
	 * @param limit
	 * @param sidx
	 * @param sord
	 * @return PageDTO
	 */
	public PageDTO findPagerCost( CostDTO queryDto, int start, int limit, String sidx, String sord  ){
		final DetachedCriteria dc = DetachedCriteria.forClass(Cost.class);
		if(queryDto!=null){
			if(queryDto.getEno()!=null){
				dc.add(Restrictions.eq("eno", queryDto.getEno()));
			}
			if(queryDto.getEventType()!=null){
				dc.add(Restrictions.eq("eventType", queryDto.getEventType()));
			}
		}
		 //排序
        if(StringUtils.hasText(sord)&&StringUtils.hasText(sidx)){
        	if("desc".equals(sord)){
        		 dc.addOrder(Order.desc(sidx));
        	}else{
        		 dc.addOrder(Order.asc(sidx));
        	}
        }else{
        	dc.addOrder(Order.desc("progressId"));
        }
        return super.findPageByCriteria(dc, start, limit);
	}
	
	/**
	 * 行程进展及成本
	 * @param queryDto
	 * @param enos
	 * @param sidx
	 * @param sord
	 * @return List<Cost>
	 */
	public List<Cost> findScheduleCost(CostDTO queryDto,List<Long> enos,String sidx, String sord){
		DetachedCriteria dc = DetachedCriteria.forClass(Cost.class);
//		dc.add(Restrictions.eq("eventType", "itsm.request"));
		dc.add(Restrictions.ne("type", "HANG"));
		if(enos!=null && enos.size()>0){
			dc.add(Restrictions.in("eno", enos));
		}
		if(queryDto!=null){
			dc.createAlias("users", "u");
			if(queryDto.getUserId()!=null && queryDto.getUserId()!=0){
				dc.add(Restrictions.eq("u.userId", queryDto.getUserId()));
			}
//			if(StringUtils.hasText(queryDto.getModule())){
//				dc.add(Restrictions.like("u.module", queryDto.getModule(), MatchMode.ANYWHERE));
//			}
			//开始时间
	    	if(queryDto.getStartTime()!=null && queryDto.getEndTime()!=null){
//	    		dc.add(Restrictions.ge("startTime", queryDto.getStartTime()));
	    		Calendar endTimeCl=new GregorianCalendar();
	        	endTimeCl.setTime(queryDto.getEndTime());
	        	endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE)+1);
	    		dc.add(Restrictions.or(
	    				Restrictions.or(
		    				Restrictions.between("startTime", queryDto.getStartTime(), queryDto.getEndTime()), 
		    				Restrictions.between("endTime", queryDto.getStartTime(),endTimeCl.getTime())
		    			),
	    				Restrictions.and(
	    						Restrictions.le("startTime", queryDto.getStartTime()),
	    						Restrictions.ge("endTime", queryDto.getEndTime())
	    				)
	    			));
	    	}
//	    	//结束时间
//	    	if(queryDto.getEndTime()!=null){
//	    		Calendar endTimeCl=new GregorianCalendar();
//	        	endTimeCl.setTime(queryDto.getEndTime());
//	        	endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE)+1);
////	    		dc.add(Restrictions.le("startTime",endTimeCl.getTime()));
//	        	
//	    	}
	    	//排序
            dc = DaoUtils.orderBy(sidx, sord, dc);
		}
		
		return super.getHibernateTemplate().findByCriteria(dc);
	}
	
	/**
	 * 时间段冲突
	 * @param dto
	 * @return Cost
	 */
	@SuppressWarnings("unchecked")
	public Cost costPeriodConflict(CostDTO dto){
		Cost cost = null;
		final DetachedCriteria dc = DetachedCriteria.forClass(Cost.class);
		dc.createCriteria("users", "user");
		dc.add(Restrictions.eq("user.userId", dto.getUserId()));
		dc.add(Restrictions.eq("eventCategoryName", "Project"));
		dc.add(Restrictions.or(
				Restrictions.or(Restrictions.between("startTime", dto.getStartTime(), dto.getEndTime()), Restrictions.between("endTime", dto.getStartTime(),dto.getEndTime())), 
				Restrictions.or(
						//查询指定时间外的
						Restrictions.and(Restrictions.lt("startTime", dto.getStartTime()),Restrictions.gt("endTime", dto.getEndTime()))
						, 
						//查询指定时间内的
						Restrictions.and(Restrictions.gt("startTime", dto.getStartTime()),Restrictions.lt("endTime", dto.getEndTime()))
						)
					));
//		dc.add(Restrictions.or(Restrictions.between("startTime", dto.getStartTime(), dto.getEndTime()), Restrictions.between("endTime", dto.getStartTime(),dto.getEndTime())));
		
		List<Cost> list = super.getHibernateTemplate().findByCriteria(dc);
		
		if(list!=null && list.size()>0)
			cost = list.get(0);
		
		return cost;
	}
	
	
	public List<Cost> findScheduleCost( Long scheduleTaskId,Date startTime,Date endTime, String taskCycle){
		List<Cost> costs = new ArrayList<Cost>();
		if ( scheduleTaskId != null ) {
			final DetachedCriteria dc = DetachedCriteria.forClass(Cost.class);
			dc.createCriteria("scheduleTask", "stask");
			dc.add( Restrictions.eq("stask.taskId", scheduleTaskId ));
			if ( ToolsConstant.TASK_TYPE_CYCLE_WEEK.equals( taskCycle )) {
				startTime = TimeUtils.getAllDayFirst( startTime );
				endTime = TimeUtils.getAllDayLast( endTime );
				dc.add( //Restrictions.between("scheduleTaskTime", dto.getStartTime(), dto.getEndTime())
					Restrictions.and(
						Restrictions.ge( "scheduleTaskTime", startTime ),
						Restrictions.le( "scheduleTaskTime", endTime )
						)
					);
			}
			dc.addOrder( Order.desc("scheduleTaskTime" ) );
			costs = super.getHibernateTemplate().findByCriteria(dc);
		}
		return costs ;
	}

	
	/**
	 * 根据任务ID删除进展及成本
	 * @param scheduleTaskIds
	 */
	public void deleteCostBySchedule(final Long[] scheduleTaskIds) {
		final DetachedCriteria dc = DetachedCriteria.forClass(Cost.class);
		dc.createCriteria("scheduleTask", "stask");
		dc.add( Restrictions.in ("stask.taskId", scheduleTaskIds ));
		deleteAll(super.getHibernateTemplate().findByCriteria(dc));
	}
}
